<template>
  <edit-dialog :centerDialogVisible="visible" :info="info" :default-button="false" :tilte="title" @Cancel="Cancel"
      @Submit="Submit" :width="width">
    <template #content>
      <div class="detail_content" style="margin-bottom: 15px;">
        <div class="image-box">
          <img v-if="!goodsObject.goodsFiles" class="content_img" :src="image.noImg" />
          <div class="image-box-top" v-else>
            <el-icon size="30px" class="image-box-top-icon" @click="changeImage('left')"
              :style="{ cursor: imageInfo.imageIndex === 0 ? 'not-allowed' : 'pointer' }" v-if="imageInfo.imgLen > 1">
              <ArrowLeftBold />
            </el-icon>
            <img :src="imageInfo.imgArr[imageInfo.imageIndex]" class="content_img"
              @click="handlePicPreview(imageInfo.imgArr[imageInfo.imageIndex])" />
            <el-icon size="30px" class="image-box-top-icon" @click="changeImage('right')"
              :style="{ cursor: imageInfo.imageIndex === imageInfo.imgLen - 1 ? 'not-allowed' : 'pointer' }"
              v-if="imageInfo.imgLen > 1">
              <ArrowRightBold />
            </el-icon>
          </div>
          <div class="image-box-bottm" v-show="imageInfo.imgLen > 1">
            <img v-for="(item, index) in imageInfo.imgArr" @click="imageInfo.imageIndex = index" :src="item" :key="item"
              :style="{ border: imageInfo.imageIndex === index ? '1px solid #555df8' : '1px solid transparent' }">
          </div>
        </div>
        <div class="detail_body">
          <div class="body_message">
            <div class="message_title">物品名称：</div>
            <div class="message_content" style="word-wrap: break-word;max-width: 300px;">{{ goodsObject.goodsName }}</div>
          </div>
          <div class="body_message">
            <div class="message_title">物品编号：</div>
            <div class="message_content">{{ goodsObject.goodsCode }}</div>
          </div>
          <div class="body_message">
            <div class="message_title">保质期：</div>
            <div class="message_content">{{ goodsObject.timeLimit }}{{ goodsObject.timeLimitUnit == 'Y' ? '年' : goodsObject.timeLimitUnit == 'H' ? '小时' : goodsObject.timeLimitUnit == 'D' ? '天' : '' }}</div>
          </div>
          <div class="body_message">
            <div class="message_title">捡拾人姓名：</div>
            <div class="message_content">{{ goodsObject.pickUpName }}</div>
          </div>
          <div class="body_message">
            <div class="message_title">航站楼[捡拾]：</div>
            <div class="message_content">{{ goodsObject.pickUpTerminal }}</div>
          </div>
          <div class="body_message">
            <div class="message_title deliver_label">是否已递送至失物招领柜台：</div>
            <div class="message_content">{{ goodsObject.taskProcess == '未接收' ? '否' : '是' }}</div>
          </div>
          <div class="body_message">
            <div class="message_title">航站楼[存放]：</div>
            <div class="message_content">{{ goodsObject.depositTerminal }}</div>
          </div>
          <div class="body_message">
            <div class="message_title">登记人：</div>
            <div class="message_content">{{ goodsObject.creator.name }}</div>
          </div>
        </div>
        <div class="detail_body">
          <div class="body_message">
            <div class="message_title">物品类型：</div>
            <div class="message_content">{{ getGoodsTypeName(goodsObject.goodsType) }}</div>
          </div>
          <div class="body_message">
            <div class="message_title">捡拾日期：</div>
            <div class="message_content">{{ goodsObject.pickUpTime ? dayjs(goodsObject.pickUpTime).format('YYYY-MM-DD HH:mm:ss') : '' }}</div>
          </div>
          <div class="body_message">
            <div class="message_title">物品时效：</div>
            <div class="message_content">{{ goodsObject.goodsLimitTime ? dayjs(goodsObject.goodsLimitTime).format('YYYY-MM-DD HH:mm:ss') : '' }}</div>
          </div>
          <div class="body_message">
            <div class="message_title">捡拾人电话：</div>
            <div class="message_content">{{ goodsObject.pickUpPhone }}</div>
          </div>
          <div class="body_message">
            <div class="message_title">捡拾地：</div>
            <div class="message_content">{{ goodsObject.pickUpPlace }}</div>
          </div>
          <div class="body_message">
            <div class="message_title">&nbsp;</div>
            <div class="message_content">&nbsp;</div>
          </div>
          <div class="body_message">
            <div class="message_title">存放地：</div>
            <div class="message_content">{{ getDepositPlaceName(goodsObject.depositPlace) }}</div>
          </div>
          <div class="body_message">
            <div class="message_title">登记时间：</div>
            <div class="message_content">{{ goodsObject.createTime ? dayjs(goodsObject.createTime).format('YYYY-MM-DD HH:mm:ss') : '' }}</div>
          </div>
        </div>
      </div>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button class="buttonCancel" @click="Cancel">关闭</el-button>
        <el-button v-if="taskProcess === '未接收'" class="buttonReceive" @click="handlerAccept" :loading="loading">接收物品</el-button>
        <el-button v-if="taskProcess === '入库审批' || taskProcess == '已接收' || taskProcess == '未接收' || taskProcess == '入库申请驳回' || taskProcess == '已出库'" class="buttonReceive" @click="handlerReceive">领取</el-button>
      </span>
    </template>
  </edit-dialog>

  <!-- 领取弹窗 -->
  <edit-dialog :centerDialogVisible="receiveDialogVisible" :tilte="title" :default-button="false" @Cancel="Cancel"
    @Submit="Submit" :width="width">
    <template #content>
      <el-form ref="receiveFormRef" :model="receiveForm" :rules="rules" label-position="right" label-width="100px">
        <el-form-item label="领取人姓名" prop="receiveName">
          <el-input v-model.trim="receiveForm.receiveName" autocomplete="off1"  placeholder="请输入领取人姓名" />
        </el-form-item>
        <el-form-item label="领取人证件号" prop="receiveNo">
          <el-input v-model.trim="receiveForm.receiveNo" autocomplete="off1" placeholder="请输入领取人证件号"/>
        </el-form-item>
        <el-form-item label="领取人电话" prop="receivePhone">
          <el-input v-model.trim="receiveForm.receivePhone" autocomplete="off1" placeholder="请输入领取人电话"/>
        </el-form-item>
        <el-form-item label="领取时间" prop="receiveTime">
          <el-date-picker v-model="receiveForm.receiveTime" type="datetime" placeholder="请选择领取时间" format="YYYY-MM-DD HH:mm:ss"/>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input type="textarea" :rows="5" v-model.trim="receiveForm.remarks" autocomplete="off1" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button class="buttonCancel" @click="handlerReceiveBack">返回</el-button>
        <el-button class="buttonReceive" @click="handlerConfirmReceive(receiveFormRef)" :loading="loading">确认领取</el-button>
      </span>
    </template>
  </edit-dialog>
  <el-dialog v-model="dialogVisible" align-center center width="auto">
    <img :src="dialogImageUrl"/>
  </el-dialog>
</template>
<script lang="ts" setup>
import editDialog from '@/components/editDialog/index.vue'
import { acceptPickPuGoods, pickUpGoodsReceive, pickUpGoodsDetail, ReceiveGoodsItem } from '@/api/lose/goodsReg'
import { reactive, ref, watch, defineProps, computed } from 'vue'
import { cloneDeep, merge } from 'lodash'
import { image } from '@/assets/index'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import dayjs from 'dayjs'
import { useStore } from 'vuex'
import { getGoodsTypeName, getDepositPlaceName } from '@/utils/common'
const width = ref('auto')
const title = ref('查看捡拾物品')
const loading = ref(false)
const receiveFormRef = ref<FormInstance>()
const receiveDialogVisible = ref(false)
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  info: {
    type: Object,
    default: null
  }
})
const imageInfo = reactive({
  imageIndex: 0,
  imgArr: [],
  imgLen: 0
})
const store = useStore()
const userInfo = computed(() => store.state.user.userInfo)
const regId = computed(() => props.info.regId)
const taskId = computed(() => props.info.taskId)
const taskProcess = computed(() => props.info.taskProcess)
const dialogImageUrl = ref('') // 图片地址
const dialogVisible = ref(false) // 图片预览弹窗
const emit = defineEmits(['cancel', 'submit', 'show'])
const receiveForm = reactive<ReceiveGoodsItem>({
  regId: '',
  taskId: '',
  receiveName: '',
  receiveNo: '',
  receivePhone: '',
  receiveTime: '',
  remarks: '',
  creator: {
    id: '',
    name: '',
    organId: '',
    organName: ''
  },
  createTime: ''
})
const validatePhone = (rule: any, value: any, callback: any) => {
  if (!value) return callback(new Error('请输入手机号'))
  if (!/^[1][3,4,5,7,8][0-9]{9}$/.test(value)) return callback(new Error('手机号格式错误'))
  callback()
}
const rules = reactive<FormRules>({
  receiveName: [{
    required: true, message: '请输入领取人姓名', trigger: 'blur'
  }],
  receivePhone: [
    { required: true, message: '请输入领取人电话', trigger: 'blur' },
    { required: true, validator: validatePhone, trigger: 'blur' }],
  receiveTime: [{
    required: true, message: '请选择领取时间', trigger: 'blur'
  }]
})

interface GoodsDataFace {
  regId: string
  goodsName: string
  goodsType: string
  goodsCode: number
  pickUpTime: string
  timeLimit: string
  timeLimitUnit: string
  goodsLimitTime: string
  pickUpName: string
  pickUpPhone: string
  pickUpTerminal: string
  pickUpPlace: string
  depositTerminal: string
  depositPlace: string
  goodsFiles?: Array<{
    enclosureContent: string
    enclosureName: string
    enclosureSuffix: string
    resourceAddress: string
    enclosureCode: string
  }>,
  creator: {
    id: string
    name: string
  }
  createTime?: string
  taskProcess: string
}

interface ReceiveDataFace {
  receiveId: number
  receiveName: string
  receiveNo: string
  receivePhone: string
  receiveTime: string
  remarks: string
  createTime: string
  creator: {
    id: string
    name: string
  }
}

const initGoodsObject = {
  regId: '',
  goodsName: '',
  goodsType: '',
  goodsCode: 0,
  pickUpTime: '',
  timeLimit: '',
  timeLimitUnit: '',
  goodsLimitTime: '',
  pickUpName: '',
  pickUpPhone: '',
  pickUpTerminal: '',
  pickUpPlace: '',
  depositTerminal: '',
  depositPlace: '',
  goodsFiles: [],
  creator: {
    id: '',
    name: ''
  },
  createTime: '',
  taskProcess: ''
}

const goodsObject = reactive<GoodsDataFace>(cloneDeep(initGoodsObject))

const initReceiveData = {
  receiveId: 0,
  receiveName: '',
  receiveNo: '',
  receivePhone: '',
  receiveTime: '',
  remarks: '',
  createTime: '',
  creator: {
    id: '',
    name: ''
  }
}
const receiveData = reactive<ReceiveDataFace>(cloneDeep(initReceiveData))
interface FileDataType {
  enclosureContent: string,
  enclosureName: string,
  enclosureSuffix: string,
  resourceAddress: string,
  enclosureCode: string,
}
const Cancel = () => {
  // Object.assign(goodsObject, initGoodsObject)
  // Object.assign(receiveData, initReceiveData)
  emit('cancel')
}
const Submit = () => {
  // Submit
}
const handlerReceive = () => {
  receiveFormRef.value?.resetFields()
  receiveDialogVisible.value = true
  title.value = '领取捡拾物品'
  width.value = 'auto'
  emit('cancel')
}

/**
* 预览图片
*/
const handlePicPreview = (url: string) => {
  dialogImageUrl.value = url
  dialogVisible.value = true
}

/**
* 切换显示图片
*/
const changeImage = (value: string) => {
  if ((value === 'left' && imageInfo.imageIndex === 0) || (value === 'right' && imageInfo.imageIndex === imageInfo.imgLen - 1)) {
    return
  }
  if (value === 'left') {
    imageInfo.imageIndex = imageInfo.imageIndex - 1
  } else {
    imageInfo.imageIndex = imageInfo.imageIndex + 1
  }
}

// 返回
const handlerReceiveBack = () => {
  receiveDialogVisible.value = false
  emit('show')
}
// 确认领取
const handlerConfirmReceive = async (formEl: FormInstance | undefined) => {
  loading.value = true
  if (!formEl) {
    loading.value = false
    return
  }
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      receiveForm.receiveTime = receiveForm.receiveTime ? dayjs(receiveForm.receiveTime).format('YYYY-MM-DD HH:mm:ss') : ''
      const payload: ReceiveGoodsItem = { ...receiveForm }
      payload.creator = {
        id: userInfo.value.userId,
        name: userInfo.value.name,
        organId: userInfo.value.organId,
        organName: userInfo.value.organName
      }
      payload.regId = regId.value
      payload.taskId = taskId.value
      const res: any = await pickUpGoodsReceive(payload)

      if (res?.code === '1') {
        receiveDialogVisible.value = false
        emit('submit')
        ElMessage.success('领取成功！')
      } else {
        ElMessage.error(res?.message || '领取失败，请重试！')
      }
      console.log('Submit!')
    } else {
      console.log('error submit!', fields)
    }
    loading.value = false
  })
}
// 接收
const handlerAccept = () => {
  const params = [{
    taskId: taskId.value,
    content: {
      creator: {
        id: userInfo.value.userId,
        name: userInfo.value.name,
        organId: userInfo.value.organId,
        organName: userInfo.value.organName
      }
    },
    swi: '2'
  }]
  loading.value = true
  console.log(params)
  acceptPickPuGoods(params).then(res => {
    if (res?.code === '1') {
      ElMessage.success('接收成功！')
      emit('submit')
    }
    loading.value = false
  }).catch(err => {
    ElMessage.error(err.message || '系统错误')
    loading.value = false
  })
}

const getPickUpGoodsDetail = () => {
  Object.assign(goodsObject, initGoodsObject)
  Object.assign(receiveData, initReceiveData)
  const params = {
    regId: regId.value,
    taskId: taskId.value
  }
  pickUpGoodsDetail(params).then(res => {
    if (res.data) {
      merge(goodsObject, res.data.goodsData)
      merge(receiveData, res.data.receiveData)
      const newImgArr: Array<string> = []
      if (res.data.goodsData?.goodsFiles?.length) {
        res.data.goodsData.goodsFiles.forEach((ele: FileDataType) => {
          ele.resourceAddress && (newImgArr.push(ele.resourceAddress))
        })
      }
      imageInfo.imgArr = newImgArr
      imageInfo.imageIndex = 0
      imageInfo.imgLen = newImgArr.length
    }
  })
}

watch(() => props.visible, (val: boolean, oldVal: boolean) => {
  if (val) {
    getPickUpGoodsDetail()
  }
})
</script>
<style lang="less" scoped>
.detail_content {
  display: flex;
  justify-items: center;
  align-items: center;
  padding: 24px;
  padding-bottom: 0px;
.image-box {
    user-select: none;

    .content_img {
      width: 240px;
      height: 180px;
      cursor: pointer;
    }

    .image-box-top {
      display: flex;
      flex-direction: row;
      align-items: center;
    }

    .image-box-bottm {
      width: 300px;
      align-items: center;
      margin-top: 10px;
      text-align: center;

      >img {
        width: 50px;
        height: 30px;
        cursor: pointer;
        margin: 0 5px;
        padding: 3px;
      }
    }
  }
  // .content_img {
  //   width: 240px;
  //   height: 240px;
  //   border-radius: 15px;
  // }

  .detail_body {
    width: auto;
    height: 240px;
    // background: rgba(238,243,255,0.56);
    border-radius: 8px;
    margin-left: 24px;
    padding-left: 24px;
    // padding-top: 16px;
    padding-bottom: 16px;
    box-sizing: border-box;

    .body_message {
      display: flex;
      line-height: 25px;

      .message_title {
        width: 100px;
        text-align: right;
        margin-bottom: 8px;
        font-size: 14px;
        font-family: HarmonyOS_Sans_SC;
        color: #989DAA;
      }
      .deliver_label{
        width: 185px;
      }
      .message_content {
        font-size: 14px;
        font-family: HarmonyOS_Sans_SC;
        color: #535862;
        margin-left: 10px;
      }
    }
  }
}

.buttonCancel {
  width: 88px;
}

.buttonReceive {
  width: 88px;
  color: #FFFFFF;
  background: #337FCC;
  border-radius: 6px;
  border: 1px solid #337FCC;
}
</style>